<template>
  <div id="register-container">
    <h1>会议室预定系统</h1>
    <el-form
      ref="formRef"
      style="max-width: 600px; margin-top: 15px"
      :model="formData"
      :rules="formRules"
      label-width="auto"
      class="demo-formData"
      :size="formSize"
      status-icon
    >
      <el-form-item label="用户名" prop="username">
        <el-input v-model="formData.username" />
      </el-form-item>
      <el-form-item label="昵称" prop="nickName">
        <el-input v-model="formData.nickName" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="formData.password" type="password" show-password />
      </el-form-item>
      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input v-model="formData.confirmPassword" type="password" show-password />
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="formData.email" />
      </el-form-item>
      <el-form-item label="验证码" prop="captcha">
        <el-input v-model="formData.captcha" style="flex: 1" />
        <el-button type="primary" class="ml-10" @click="sendCaptcha" :disabled="isSendCaptcha">{{
          isSendCaptcha ? `${countdown} 秒后重新获取` : '发送验证码'
        }}</el-button>
      </el-form-item>
      <div style="text-align: right; font-size: 12px">
        已有帐号?去 <span style="color: var(--main-color)">登录</span>
      </div>
      <el-row justify="center">
        <el-form-item>
          <el-button type="primary" @click="submitForm(formRef)"> 注册 </el-button>
        </el-form-item>
      </el-row>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { registerCaptcha, register } from '@/api'
import { ElMessage, type ComponentSize, type FormInstance, type FormRules } from 'element-plus'
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'

export interface IRegisterUser {
  username: string
  nickName: string
  password: string
  confirmPassword: string
  email: string
  captcha: string
}

const formSize = ref<ComponentSize>('default')
const formRef = ref<FormInstance>()
const countdown = ref(0)
const isSendCaptcha = ref(false)
let timer: number | undefined | null = null
const router = useRouter()

const formData = reactive<IRegisterUser>({
  username: '',
  nickName: '',
  password: '',
  confirmPassword: '',
  email: '',
  captcha: ''
})
const formRules = reactive<FormRules<IRegisterUser>>({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 1, max: 10, message: '长度在1 到 10 个字符', trigger: 'blur' }
  ],
  nickName: [{ required: true, message: '请输入昵称', trigger: 'blur' }],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码不能少于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请输入确认密码', trigger: 'blur' },
    // 两次密码输入不一致验证
    {
      validator: (rule, value, callback) => {
        if (value !== formData.password) {
          callback(new Error('两次密码输入不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  captcha: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入合法邮箱', trigger: 'blur' }
  ]
})

const sendCaptcha = async () => {
  if (!formData.email) {
    ElMessage.warning('请输入邮箱')
    return
  }
  const res = await registerCaptcha(formData.email)
  if (res.status === 200 || res.status === 201) {
    ElMessage.success('验证码发送成功')
    startCountdown(60)
  }
}

const startCountdown = (time: number) => {
  countdown.value = time
  isSendCaptcha.value = true
  timer = setInterval(() => {
    countdown.value--
    if (countdown.value === 0) {
      clearInterval(timer as number)
      isSendCaptcha.value = false
    }
  }, 1000)
}

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async (valid, fields) => {
    if (valid) {
      const res = await register(formData)
      const { code, message: msg, data } = res.data
      if (res.status === 200 || res.status === 201) {
        ElMessage.success('注册成功')
        // 跳转至登陆页面
        setTimeout(() => {
          router.push({ name: 'login' })
        }, 1500)
      } else {
        ElMessage.error(data || '系统繁忙,请稍后再试')
      }
    } else {
      ElMessage.error('表单校验失败')
    }
  })
}
</script>

<style scoped lang="less">
#register-container {
  width: 400px;
  margin: 100px auto 0 auto;
  text-align: center;
}
</style>
